import { parse } from "qs";
import { message } from "antd";
import moment from "moment";
import { isEmpty, isArray, cloneDeep, merge } from "lodash";
import { hashHistory } from "dva/router";
import { getStatusUpDate,queryAllAddress } from "./advertisingWindowListServ.js";
import { makeAddress } from "utils/util";

const defultState = {
  biz: {},
};

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        if ("" + tmpModule.pathname === "" + pathname) {
          dispatch({ type: "updateStore", payload: {} });
          dispatch({ type: "getAreaList", payload: {} });
        }
      });
    },
  },

  effects: {
    *getAreaList({ payload }, { put, call, select }) {
      const { data, success } = yield call(queryAllAddress);
      if (success) {
        let arr = [];
        data.map((item, index) => {
          arr.push(item.value);
        });
        let areaList = [];

        let arr1 = [data[0]];
        let attr = [data[data.length - 1]];
        let firtOpt = data[0];
        let lastOpt = data[data.length - 1];
        // 返回数据有北京\澳门需要特别处理
        if (firtOpt["value"] == "110100") {
          data[0] = {
            label: "北京",
            value: "110100",
            children: arr1,
          };
        }

        if (lastOpt["value"] == "820000") {
          data[data.length - 1] = {
            label: "澳门",
            value: "820000",
            children: attr,
          };
        }
        areaList = makeAddress(data, 2);
        console.log(areaList);
        yield put({ type: "updateStore", payload: { areaList } });
      }
    },
    //更新状态与删除
    *updateStatus({ payload }, { put, call, select }) {
      try {
        console.log(payload, "payload");
        const { rows, success, total, pageNo } = yield call(
          getStatusUpDate,
          payload
        );
        let defultState = yield select((state) => state[tmpModule.namespace]);
        if (success) {
          message.success(payload.delete ? "删除成功" : "更新成功", () => {
            defultState.biz.refreshListDatas(true);
          });
        }
      } catch (e) {
        console.error(e);
      }
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      console.log(preState.city);
      return Object.assign({}, preState, action.payload);
    },
  },
};

export default tmpModule;
